const router = require('koa-router')();
const {getDbHelper, httpClient, dbs} = require('../../libs');

router.prefix('/db');

/**
 * 查看数据库表
 */
router.get('/tables', async (ctx, next) => {
    let dbIndex = ctx.query.dbIndex || 0;
    let schema = ctx.query.schema || 'mysql';
    let dbType = ctx.query.dbType;

    await ctx.render('db/tables', {
        title: '数据表一览',
        dbs: dbs,
        dbIndex: dbIndex,
        schema: schema,
        dbType: dbType
    });
});

router.post('/table/:dbIndex/:dbType/:dbName/:tableName', async (ctx, next) => {
    let dbIndex = ctx.params.dbIndex || 0;
    let dbType = ctx.params.dbType;
    let dbName = ctx.params.dbName || 0;
    let tableName = ctx.params.tableName || '';
    let hosts = ctx.request.headers.host.split(':');

    let data;

    await httpClient.get(`http://${hosts[0]}:${hosts[1]}/api/${dbType}/${dbIndex}/${dbName}/${tableName}/columns`).then(
        res => data = {
            rows: JSON.parse(res.body),
            rowsJson: res.body
        },
        reason => data = reason
    );

    await ctx.render('db/_columns', data);
});

/**
 * 查看数据库状态。
 */
router.get('/status/:dbIndex', async (ctx, next) => {
    let dbIndex = ctx.params.dbIndex || 0;
    let db = dbs[dbIndex];

    await ctx.render('db/status', {
        title: '数据库状态',
        dbIndex: dbIndex,
        dbs: dbs,
        db: db
    });
});

module.exports = router;